/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitsolo.htm
 *
 * gitsolo is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitsolo.interceptor;

import org.zhiqim.gitsolo.GitsoloConstants;
import org.zhiqim.gitsolo.dao.GitProjectDao;
import org.zhiqim.gitsolo.dbo.GitProject;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.httpd.context.core.Interceptor;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.manager.ZmrSessionUser;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;

/**
 * 检查是否有效的工程的拦截器
 *
 * @version v1.0.0 @author zouzhigang 2016-10-24 新建与整理
 */
@AnAlias("chkProject")
public class GitProjectInterceptor implements Interceptor, GitsoloConstants
{
    @Override
    public void intercept(HttpRequest request) throws Exception
    {
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        long projectId = sessionUser.getOperatorParamLong(GIT_PROJECT_ID_KEY);
        if (projectId == -1)
        {
            if (request.getParameterBoolean(_PARAM_DIALOG_FRAME_))
                request.returnCloseDialog("请选择一个有效的项目");
            else
                request.setRedirect(request.getRootPath("/zhiqim_project/project.htm"), "请选择一个有效的项目");
            return;
        }
        
        if (ORM.table().count(GitProject.class, new Selector("projectId", projectId).addMust("projectStatus", 0)) == 0)
        {//当前项目已删除或被停用，或成员被删除
            
            //重新选择默认项目
            GitProjectDao.doActiveProject(request,sessionUser);
            projectId = sessionUser.getOperatorParamLong(GIT_PROJECT_ID_KEY);
            if (projectId == -1)
            {//仍没有项目
                if (request.getParameterBoolean(_PARAM_DIALOG_FRAME_))
                    request.returnCloseDialog("请选择一个有效的项目");
                else
                    request.setRedirect(request.getRootPath("/zhiqim_project/project.htm"), "请选择一个有效的项目");
                return;
            }
        }
    }
}
